//配置文件路径
const configPath = "/sdcard/lucky-bag-triumph.txt"

var configData = readConfig()

//读配置文件数据
function readConfig () {
    let params = {}
    try {
        let p = files.read(configPath)
        params = JSON.parse(p)
    } catch (e) {
        console.log("读取配置文件数据异常:" + e)
    }
    return params
}


//更新卡密信息
function updateCardInfo (params) {
    threads.start(function () {
        try {
            //卡密
            let keygen = params.keygen
            if (!keygen) {
                toastLog("请输入卡密")
                return
            }
            var url = "http://43.138.184.61:7151/app-api/verify/card/bind";
            // var url = "http://192.168.31.212:48080/app-api/verify/card/bind";
            let id;
            if (device.sdkInt < 29) {
                id = device.getIMEI();
            } else {
                id = device.getAndroidId();
            }
            let deviceId = null;
            try {
                let p = files.read(configPath)
                p = JSON.parse(p)
                if (p.deviceId === undefined || p.deviceId === null || p.deviceId === "") {
                    deviceId = id;
                } else {
                    deviceId = p.deviceId;
                }
            } catch (e) {
                deviceId = id;
            }
            let r = http.postJson(url, {
                "cardNumber": keygen,
                "cardDeviceNumber": deviceId
            });
            let d = JSON.parse(r.body.string())
            let msg
            if (d.code === 0) {
                msg = "激活成功"
            } else {
                msg = d.msg
            }
            params.jh_result = msg
            params.deviceId = deviceId
            configData = params
            params = JSON.stringify(params)
            files.write(configPath, params);
            toastLog(msg)
        } catch (e) {
            console.log(e)
            toastLog("卡密服务异常,请检查网络")
        }
    });
}

//效验卡密信息
function checkCar () {
    let keygen = ui.keygen.text()
    if (!keygen) {
        toastLog("请输入卡密")
        return false
    }
    let jh = configData.jh_result
    if (jh === "激活成功") {
        return true
    } else {
        toastLog(jh)
        return false;
    }
}

exports.checkCar = checkCar;
exports.updateCardInfo = updateCardInfo;
exports.readConfig = readConfig;